#include "serialserver.h"

#include <QtDebug>
#include <QThread>
#include <QEventLoop>
#include "io/io.h"
#include <QMutexLocker>
#include <QDateTime>
#include "packetparser.h"

#define RECEIVE_DURATION 300

SerialServer::SerialServer(QString portName, QObject *parent) :
    QObject(parent),
    mPortName(portName),
    mpSerialPort(nullptr),
    mParser([this](QByteArray& data){received(data);})
{
}

SerialServer::~SerialServer() {
    close();
}

QString SerialServer::portName() {
    return mPortName;
}

void SerialServer::listen() {
    if (!mpSerialPort) {
        qDebug() << "server::listen()";
        mpSerialPort = new SerialPort(mPortName);
        connect(mpSerialPort, &SerialPort::readyRead,
                [this]{
                    int toRead = mpSerialPort->bytesAvailable();
                    if (toRead > 0) {
                        QByteArray buff = mpSerialPort->read(toRead);
                        dump("raw", buff); // TODO remove
                        mParser.parser(buff);
                    }
                });

        // open serial port
        mpSerialPort->open(QIODevice::ReadWrite);
    }
}

void SerialServer::close() {
    if (mpSerialPort) {
        mpSerialPort->close();
        mpSerialPort = nullptr;
    }
}

qint64 SerialServer::send(QByteArray bytes) {
    if (!mpSerialPort) {
        return -1;
    }

    QByteArray encoded = PacketParser::encode(bytes);
    return IO::copy("send", encoded, mPortName, *mpSerialPort, bytes.size());
}

void SerialServer::dump(QString tag, QByteArray& bytes) {
    QStringList list;
    for (auto& byte : bytes) {
        list << QString::asprintf("%02X", byte & 0x00FF);
    }

    qDebug() << "[" << tag << "] " << list.join(" ");
}
